package weaver.interfaces.zhlx.duss.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
import weaver.common.DateUtil;
import weaver.conn.RecordSet;
import weaver.file.ImageFileManager;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.BaseBean;
import weaver.general.TimeUtil;
import weaver.general.Util;

import java.io.*;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author dusongsong
 * @date 2024年11月28日 13:49
 */
public class CrmUtil extends BaseBean {

    private static final MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
    private static final int CONNECT_TIMEOUT_MILLIS = 60 * 1000; // 60秒
    private static final int READ_TIMEOUT_MILLIS = 60 * 1000; // 60秒
    private static final int WRITE_TIMEOUT_MILLIS = 60 * 1000; // 60秒
    private OkHttpClient client;
    // 定义常量
    private static final String RES_CODE_ZERO = "0";

    public CrmUtil() {
        this.client = new OkHttpClient.Builder()
                .hostnameVerifier(new AllowAllHostnameVerifier())
                .connectTimeout(CONNECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)
                .readTimeout(READ_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)
                .writeTimeout(WRITE_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)
                .build();
    }

    /**
     * 调用接口执行
     *
     * @param dataJson
     * @param dataMap
     * @param apiName
     * @return
     */
    public JSONObject excuteHandler(JSONObject dataJson, Map<String, Object> dataMap, String apiName) {
        JSONObject paramJson = new JSONObject();
        JSONObject resultJson = new JSONObject();
        JSONObject propVal = PropUltraUtil.getPropMainVal("zhlxcrm");
        String base_url = propVal.getString("url");
        String username = propVal.getString("username");
        String mainid = propVal.getString("mainid");
        JSONObject propValJson = PropUltraUtil.getPropDtlVal(mainid, apiName);
        String apiUrl = base_url + propValJson.getString("jkdz");
        JSONObject accessTokenJson = getAccessToken();
        if (!accessTokenJson.isEmpty()) {
            String corpId = accessTokenJson.getString("corpId");
            String corpAccessToken = accessTokenJson.getString("corpAccessToken");
            paramJson.put("corpId", corpId);
            paramJson.put("corpAccessToken", corpAccessToken);
            paramJson.put("currentOpenUserId", username);
            paramJson.put("data", dataJson);
            writeLog(">>>>>excuteHandler>>>>>paramJson:" + paramJson.toJSONString());
            resultJson = sendOKHttpPostRequest(apiUrl, paramJson.toJSONString());
            writeLog(">>>>>excuteHandler>>>>>resultJson:" + resultJson.toJSONString());
            dataMap.put("jkqqcs", paramJson);
            dataMap.put("jkxycs", resultJson);
            insertApiLog(dataMap, apiUrl);
        } else {
            resultJson.put("message", "获取应用级授权失败");
        }
        return resultJson;
    }

    public JSONArray getImagefile(String docid) {
        RecordSet rs = new RecordSet();
        JSONArray retrunArray = new JSONArray();
        rs.executeQuery("select imagefileid,imagefilename from DocImageFile where docid=?", docid);
        if (rs.next()) {
            JSONObject retrunJson = new JSONObject();
            int imagefileid = Util.getIntValue(rs.getString("imagefileid"));
            String imagefilename = Util.null2String(rs.getString("imagefilename"));
            String filetype = imagefilename.substring(imagefilename.lastIndexOf(".")+1);
            String filesize = getFilesize(imagefileid);
            InputStream inputStream = ImageFileManager.getInputStreamById(imagefileid);
            String fileName = "/usr/weaver/ecology/sapfile/" + imagefilename;
            boolean flag = createImageFile(inputStream, fileName);
            writeLog(">>>>>getImagefile>>>>>flag=" + flag);
            File file = new File(fileName);
            JSONObject resultJson = sendOKHttpMultipartFile(imagefilename, file);
            writeLog(">>>>>getImagefile>>>>>resultJson=" + resultJson.toJSONString());
            String message = resultJson.getString("message");
            if ("success".equals(message)) {
                JSONObject dataJson = resultJson.getJSONObject("data");
                String mediaId = dataJson.getString("mediaId");
                retrunJson.put("ext", filetype);
                retrunJson.put("path", mediaId);
                retrunJson.put("filename", imagefilename);
                retrunJson.put("create_time", System.currentTimeMillis());
                retrunJson.put("size", filesize);
                retrunArray.add(retrunJson);
            }
            String deleteFileResult = deleteFileByName(fileName);
            writeLog(">>>>>getImagefile>>>>>deleteFileResult=" + deleteFileResult);
        }
        return retrunArray;
    }


    private String getFilesize(int imagefileid) {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select filesize from ImageFile where imagefileid =?", imagefileid);
        rs.next();
        return Util.null2String(rs.getString("filesize"));
    }

    public static boolean createImageFile(InputStream inputStream, String fileName) {
        OutputStream outputStream = null;
        boolean flag = false;
        try {
            // 创建一个 OutputStream 对象，用于写入目标文件
            outputStream = new FileOutputStream(fileName);
            // 创建一个缓冲区，用于存储读取的数据
            byte[] buffer = new byte[1024];
            int bytesRead;
            // 读取 InputStream 中的数据，并写入 OutputStream
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            flag = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭流
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return flag;
    }


    /**
     * 获取应用级授权
     *
     * @return
     */
    private JSONObject getAccessToken() {
        JSONObject propVal = PropUltraUtil.getPropMainVal("zhlxcrm");
        String base_url = propVal.getString("url");
        String mainid = propVal.getString("mainid");
        JSONObject propValJson = PropUltraUtil.getPropDtlVal(mainid, "getToken");
        String apiUrl = base_url + propValJson.getString("jkdz");
        writeLog(">>>>>getAccessToken>>>>>apiUrl:" + apiUrl);
        JSONObject paramJson = new JSONObject();
        JSONObject resultJson = new JSONObject();
        paramJson.put("appId", propValJson.getString("appid"));
        paramJson.put("appSecret", propValJson.getString("appsecret"));
        paramJson.put("permanentCode", propValJson.getString("permanentcode"));
        writeLog(">>>>>getAccessToken>>>>>paramJson:" + paramJson.toJSONString());
        JSONObject retrunJson = sendOKHttpPostRequest(apiUrl, paramJson.toJSONString());
        writeLog(">>>>>getAccessToken>>>>>retrunJson:" + retrunJson.toJSONString());
        String message = retrunJson.getString("message");
        if ("success".equals(message)) {
            JSONObject resultJsonObj = retrunJson.getJSONObject("data");
            String errorCode = resultJsonObj.getString("errorCode");
            if (RES_CODE_ZERO.equals(errorCode)) {
                String corpAccessToken = resultJsonObj.getString("corpAccessToken");
                String corpId = resultJsonObj.getString("corpId");
                resultJson.put("corpAccessToken", corpAccessToken);
                resultJson.put("corpId", corpId);
            }
        }
        return resultJson;
    }

    /**
     * Post请求
     *
     * @param params
     * @param apiUrl
     * @return
     */
    public JSONObject sendOKHttpPostRequest(String apiUrl, String params) {
        JSONObject resultJson = new JSONObject();
        String responseMsg = "";
        try {
            RequestBody body = RequestBody.create(mediaType, params);
            Request request = new Request.Builder()
                    .url(apiUrl)
                    .method("POST", body)
                    .addHeader("Content-Type", "application/json")
                    .build();
            Response response = client.newCall(request).execute();
            String responseStr = Util.null2String(response.body().string());
            response.body().close(); // 保证资源被释放
            // 增加对HTTP状态码的检查
            if (!response.isSuccessful()) {
                responseMsg = "response code :" + response.code();
            } else {
                if (!responseStr.isEmpty()) {
                    resultJson.put("data", responseStr);
                    responseMsg = "success";
                } else {
                    responseMsg = "response result is null";
                }
            }
        } catch (Exception e) {
            responseMsg = "response timeout or network error";
            writeLog(">>>>>sendOKHttpPostRequest>>>>>Exception e:", e);
        }
        resultJson.put("message", responseMsg);
        return resultJson;
    }

    /**
     * 上传文件
     *
     * @param filename
     * @param file
     * @return
     */
    public JSONObject sendOKHttpMultipartFile(String filename, File file) {
        JSONObject resultJson = new JSONObject();
        String responseMsg = "";
        JSONObject propVal = PropUltraUtil.getPropMainVal("zhlxcrm");
        String base_url = propVal.getString("url");
        JSONObject accessTokenJson = getAccessToken();
        if (!accessTokenJson.isEmpty()) {
            String corpId = accessTokenJson.getString("corpId");
            String corpAccessToken = accessTokenJson.getString("corpAccessToken");
            try {
                RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
                        .addFormDataPart("media", filename,
                                RequestBody.create(MediaType.parse("application/octet-stream"), file))
                        .addFormDataPart("corpAccessToken", corpAccessToken)
                        .addFormDataPart("corpId", corpId)
                        .addFormDataPart("type", "document")
                        .build();
                Request request = new Request.Builder()
                        .url(base_url + "/media/upload")
                        .method("POST", body)
                        .addHeader("Accept", "*/*")
                        .addHeader("Connection", "keep-alive")
                        .addHeader("Content-Type", "multipart/form-data;")
                        .build();
                Response response = client.newCall(request).execute();
                String responseStr = Util.null2String(response.body().string());
                response.body().close(); // 保证资源被释放
                // 增加对HTTP状态码的检查
                if (!response.isSuccessful()) {
                    responseMsg = "response code :" + response.code();
                } else {
                    if (!responseStr.isEmpty()) {
                        resultJson.put("data", responseStr);
                        responseMsg = "success";
                    } else {
                        responseMsg = "response result is null";
                    }
                }
            } catch (Exception e) {
                responseMsg = "response timeout or network error";
                writeLog(">>>>>sendOKHttpMultipartFile>>>>>Exception e:", e);
            }
        } else {
            resultJson.put("message", "获取应用级授权失败");
        }
        resultJson.put("message", responseMsg);
        return resultJson;
    }


    /**
     * 插入接口日志
     *
     * @param dataMap
     * @param apiUrl
     */
    private void insertApiLog(Map<String, Object> dataMap, String apiUrl) {
        String fullDate = DateUtil.getFullDate();
        try {
            InetAddress address = InetAddress.getLocalHost();
            String serverIp = address.getHostAddress();
            dataMap.put("fwqdz", serverIp);
            dataMap.put("jkqqdz", apiUrl);
            dataMap.put("jkdysj", fullDate);
            dataMap.put("jktgf", "CRM");
            insertModelData("uf_apilog", dataMap);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

    }

    //建模权限重构
    private void newModeRight(int userid, int formmodeid, int id) {
        ModeRightInfo modeRightInfo = new ModeRightInfo();
        modeRightInfo.setNewRight(true);
        modeRightInfo.editModeDataShare(userid, formmodeid, id);
    }

    //将数据插入表单建模
    private int insertModelData(String tablename, Map<String, Object> map) {
        int dataid = 0;
        int userid = 1;
        RecordSet rs = new RecordSet();
        RecordSet rs1 = new RecordSet();
        //查询该模块表名
        try {
            String sql = "select a.id from modeinfo a left join workflow_bill b on a.formid=b.id where b.tablename=?";
            rs.executeQuery(sql, tablename);
            rs.next();
            int modeid = Util.getIntValue(rs.getString("id"));
            String uuid = UUID.randomUUID().toString();
            String insSql = "insert into " + tablename
                    + "(modeuuid,modedatacreater,modedatacreatedate,modedatacreatetime,formmodeid)values(?,?,?,?,?)";
            Object[] params = {uuid, userid, TimeUtil.getCurrentDateString(), TimeUtil.getOnlyCurrentTimeString(), modeid};
            if (rs.executeUpdate(insSql, params)) {
                rs1.executeQuery("select id from " + tablename + " where modeuuid=?", uuid);
                rs1.next();
                dataid = Util.getIntValue(rs1.getString("id"));
                if (dataid > 0) {
                    //遍历数据 进行update
                    String updatesql = "update " + tablename + " set ";
                    Set<String> keySet = map.keySet();
                    for (String key : keySet) {
                        updatesql += key + "='" + map.get(key).toString() + "',";
                    }
                    if (updatesql.endsWith(",")) {
                        updatesql = updatesql.substring(0, updatesql.length() - 1);
                        updatesql += " where id=" + dataid;
                        if (!rs.executeUpdate(updatesql)) {
                            rs1.executeUpdate("delete from " + tablename + " where id=?", dataid);
                        }
                    }
                    //进行权限重构
                    newModeRight(userid, modeid, dataid);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return dataid;
    }

    /*
     *@Description: 将时间转换为时间戳
     */
    public String dateToStamp(String s) {
        String res = "";
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = simpleDateFormat.parse(s);
            long ts = date.getTime();
            res = String.valueOf(ts);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return res;
    }

    public String deleteFileByName(String filePath) {
        // 创建 File 对象
        File file = new File(filePath);
        String message = "";
        try {
            // 检查文件是否存在
            if (file.exists()) {
                // 尝试删除文件
                boolean isDeleted = file.delete();
                if (isDeleted) {
                    message = "文件删除成功";
                } else {
                    message = "文件删除失败";
                }
            } else {
                message = "文件不存在";
            }
        } catch (Exception e) {
            message = "发生错误";
            e.printStackTrace();
        }
        return message;
    }


}
